package stark.app.function.recorder;

import android.Manifest;
import android.annotation.SuppressLint;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.stark.audio.edit.AudioVoiceChangeActivity;
import com.stark.media.recorder.AudioRecorder;
import com.stark.media.recorder.IRecStateListener;
import com.stark.media.recorder.RecState;

import java.io.File;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.app.R;
import stark.app.databinding.FragmentAudioRecBinding;
import stark.app.function.screenshot.ScreenRecAdapter;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.utils.FastClickUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.TimeUtil;

/**
 * Author：daizhongbin on 2021/7/8
 * Email：1027154338@qq.com
 * Desc:
 */
public class AudioRecDemoFragment extends BaseNoModelFragment<FragmentAudioRecBinding> {

    private AudioRecorder mAudioRecorder;
    private ScreenRecAdapter mRecAdapter;
    private Handler mHander = new Handler();
    private Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            long duration = mAudioRecorder.getRecDuration();
            String strTime = TimeUtil.getHHmmss(duration);
            mDataBinding.tvTime.setText(strTime);
            mHander.postDelayed(this, 500);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.fragment_audio_rec;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initView() {
        mAudioRecorder = AudioRecorder.getInstance();
        mAudioRecorder.addStateListener(mStateListener);
        mDataBinding.btnStartStopRec.setOnClickListener(v -> {
            if (FastClickUtil.isFastClick()) return;
            RecState state = mAudioRecorder.getRecordState();
            if (state == RecState.IDLE) {
                PermissionUtils.permission(Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .callback(new PermissionUtils.SingleCallback() {
                            @Override
                            public void callback(boolean isAllGranted, @NonNull List<String> granted, @NonNull List<String> deniedForever, @NonNull List<String> denied) {
                                if (isAllGranted) {
                                    mAudioRecorder.start();
                                } else {
                                    ToastUtils.showShort(com.stark.common.res.R.string.permission_no_granted);
                                }
                            }
                        })
                        .request();
            } else {
                if (mAudioRecorder.canStop()) {
                    mAudioRecorder.stop();
                } else {
                    ToastUtils.showShort("录制时长不能少于" + (mAudioRecorder.getMinRecDuration() / 1000) + "秒");
                }
            }
        });
        mDataBinding.btnPauseResumeRec.setOnClickListener(v -> {
            if (FastClickUtil.isFastClick()) return;
            RecState state = mAudioRecorder.getRecordState();
            if (state == RecState.RECORDING) {
                mAudioRecorder.pause();
            } else if (state == RecState.PAUSE) {
                mAudioRecorder.resume();
            }
        });

        //rv
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mDataBinding.rvRecords.setLayoutManager(layoutManager);
        ScreenRecAdapter recAdapter = new ScreenRecAdapter();
        mRecAdapter = recAdapter;
        recAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                String filePath = recAdapter.getItem(position).getAbsolutePath();
                AudioVoiceChangeActivity.start(getContext(), filePath);
            }
        });
        mDataBinding.rvRecords.setAdapter(recAdapter);
    }

    @Override
    protected void initData() {
        RxUtil.create(new RxUtil.Callback<List<File>>() {
            @Override
            public void doBackground(ObservableEmitter<List<File>> emitter) {
                emitter.onNext(loadRecords());
            }

            @Override
            public void accept(List<File> fileList) {
                if (fileList == null || fileList.size() == 0) {
                    mDataBinding.tvNoData.setVisibility(View.VISIBLE);
                } else {
                    mDataBinding.tvNoData.setVisibility(View.GONE);
                    mRecAdapter.setNewInstance(fileList);
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mAudioRecorder != null) {
            mAudioRecorder.release();
        }
    }

    private List<File> loadRecords() {
        String recFolder = mAudioRecorder.getRecFolder();
        return FileUtils.listFilesInDir(recFolder);
    }

    private IRecStateListener mStateListener = new IRecStateListener() {

        @Override
        public void onStateChanged(RecState state) {
            if (state == RecState.RECORDING) {
                //录制中
                mHander.post(mTaskUpdateTime);
                mDataBinding.btnStartStopRec.setText("停止录制");
                mDataBinding.btnPauseResumeRec.setText("暂停录制");
                mDataBinding.btnPauseResumeRec.setVisibility(View.VISIBLE);
            } else if (state == RecState.PAUSE) {
                //录制暂停
                mHander.removeCallbacks(mTaskUpdateTime);
                mDataBinding.btnStartStopRec.setText("停止录制");
                mDataBinding.btnPauseResumeRec.setText("恢复录制");
                mDataBinding.btnPauseResumeRec.setVisibility(View.VISIBLE);
            } else {
                //录制结束
                mHander.removeCallbacks(mTaskUpdateTime);
                mDataBinding.btnStartStopRec.setText("开始录制");
                mDataBinding.btnPauseResumeRec.setVisibility(View.GONE);
                String filePath = mAudioRecorder.getRecFilePath();
                if (TextUtils.isEmpty(filePath)) {
                    return;
                }
                if (mRecAdapter != null) {
                    try {
                        mRecAdapter.addData(new File(filePath));
                        mDataBinding.tvNoData.setVisibility(View.GONE);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    };
}
